package com.rrd.hive.udf;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Description(
        name = "week_num",
        value = "_FUNC_(date, firstDay) - Get week num of the year; 1-SUNDAY,2-MONDAY,3-TUESDAY,4-WEDNESDAY,5-THURSDAY,6-FRIDAY,7-SATURDAY",
        extended = "Example:\n> SELECT _FUNC_('2021-05-01');\n  18\n> SELECT _FUNC_('2021-05-01', 7);\n  19"
)
public class WeekNumUDF extends UDF {

    public Text evaluate(String date){
        return evaluate(date, 2);
    }

    public Date parse(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public Text evaluate(String date, Integer firstDay) {
        if (firstDay < 1 || firstDay > 7) {
             return null;
        }
        Date sd = parse(date);
        if (sd == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(firstDay);
        cal.setTime(sd);
        int num = cal.get(Calendar.WEEK_OF_YEAR);
        Text text = new Text();
        text.set(String.valueOf(num));
        return text;
    }


    public static void main(String[] args) {
        WeekNumUDF dfu = new WeekNumUDF();
        System.out.println(dfu.evaluate("2021-05-01", 7));
    }
}
